# -*- coding: utf-8 -*-
# @Time    : 2020/7/17 13:54
# @Author  : ZhaoHexin
# @File    : BatchEncodeSso.py
# @Description  : 批量创建sso

import os
import time
import csv
import json

from config import InfoConfig
from CreateSsoFile.CreateSso import CreateSso


class BatchEncodeSso:
    def __init__(self, progressBarValue, mywindows):
        self.path = InfoConfig.path
        self.user_names = InfoConfig.usernames
        self.passwords = InfoConfig.passwords
        self.majorcodes = InfoConfig.majorcodes
        self.majornames = InfoConfig.majornames
        self.progressBarValue = progressBarValue
        self.mywindows = mywindows
        self.batch_encryption_path = InfoConfig.batch_encryption_path
        self.csv_info = self.read_file()

    def read_file(self):
        """
        读取csv数据
        :return:
        """
        csvfile = open(self.batch_encryption_path, 'r', encoding='utf-8')
        # 指定列名
        fieldnames = ("path", "regioncode", "username", "password")
        reader = csv.DictReader(csvfile, fieldnames)
        # 指定ensure_ascii=False 为了不让中文显示为ascii字符码
        out = json.loads(json.dumps([row for row in reader], ensure_ascii=False))
        out.pop(0)
        return out

    def makdir(self, dir_path):
        """
        创建文件夹
        :return:
        """
        try:
            os.makedirs(dir_path)
        except Exception as e:
            pass

    def create_sso(self):
        """
        创建sso
        :return:
        """
        # 创建文件夹
        for i in range(len(self.csv_info)):
            self.progressBarValue.emit(i * 100 / len(self.csv_info))  # 发送进度条的值 信号
            self.create(self.csv_info[i])
        self.progressBarValue.emit(100)
        self.mywindows.textBrowser_2.append("")
        self.mywindows.textBrowser_2.append("恭喜，批量文件加密成功了哦！以下是sso相关信息，请查看-")
        self.mywindows.textBrowser_2.append("")
        self.mywindows.textBrowser_2.append(f"文件路径为：{InfoConfig.path}")
        self.mywindows.textBrowser_2.append("")
        # 解锁
        InfoConfig.is_click = True

    def create(self, csv):
        """
        分条创建sso
        :param data:
        :return:
        """
        dir_path = self.path

        dir_path = os.path.join(dir_path, csv.get("path"))
        # 进行文件创建
        self.makdir(dir_path)
        regioncode = csv.get("regioncode")
        username = [csv.get("username")] if csv.get("username") != "" else self.user_names
        password = [csv.get("password")] if csv.get("password") != "" else self.passwords
        CreateSso(username, password, self.majorcodes, self.majornames, [regioncode], dir_path).create()
        print(f"****************************************")
        print(f"创建{regioncode}完成")
        print(f"****************************************")
        print(time.ctime())


if __name__ == '__main__':
    InfoConfig.usernames = ["user666"]
    InfoConfig.passwords = ["1"]
    InfoConfig.majorcodes = ["2019ydldldc_00GJ"]
    InfoConfig.majornames = []
    InfoConfig.path = os.path.abspath(".")
    InfoConfig.batch_encryption_path = "D:\Codes\SsoCreate\ssoFiles.csv"
    BatchEncodeSso().create_sso()
